package com.ws.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ws.eduservice.entity.EduSubject;
import com.ws.eduservice.entity.excel.ExcelSubject;
import com.ws.eduservice.service.EduSubjectService;
import com.ws.servicebase.exceptionhandler.MyException;

/**
 * @author ws
 * @create 2024-12-04 09:57
 */
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubject> {

    public EduSubjectService subjectService;
    public SubjectExcelListener() {};
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(ExcelSubject excelSubject, AnalysisContext analysisContext) {
        if (excelSubject == null) {
            throw new MyException(20001,"文件内容为空");
        }
        EduSubject existOneSubject = existOneSubjectName(subjectService, excelSubject.getOneSubjectName());
        if (existOneSubject==null) {
            existOneSubject= new EduSubject();
            existOneSubject.setTitle(excelSubject.getOneSubjectName());
            existOneSubject.setParentId("0");
            subjectService.save(existOneSubject);
        }
        String id = existOneSubject.getId();
        EduSubject existTwoSubject = existTwoSubjectName(subjectService, excelSubject.getTwoSubjectName(), id);
        if (existTwoSubject==null) {
            existTwoSubject= new EduSubject();
            existTwoSubject.setTitle(excelSubject.getTwoSubjectName());
            existTwoSubject.setParentId(id);
            subjectService.save(existTwoSubject);
        }

    }
        //判断一级分类的名称是否重复
    private EduSubject existOneSubjectName(EduSubjectService subjectService,String name) {
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",0);
        EduSubject one = subjectService.getOne(queryWrapper);
        return one;

    }
    //判断二级分类的名称是否重复
    private EduSubject existTwoSubjectName(EduSubjectService subjectService,String name,String parentId) {
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",parentId);
        EduSubject two = subjectService.getOne(queryWrapper);
        return two;

    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
